package com.kob.botrunningsystem.utils;

import com.kob.botrunningsystem.pojo.Bot;

import java.awt.geom.QuadCurve2D;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 虽然队列没用消息队列，但是因为我们写了条件变量与锁的操作，所以等价于消息队列BotPool
 */
public class BotPool extends Thread {

    // 以下的锁和条件变量加不加static都可以，因为BotPool只有一个
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();    //线程类
    private final Queue<Bot> bots = new LinkedList<>();        //队列

    //生产者
    public void addBot(Integer userId, String botCode, String input) {
        lock.lock();
        try {
            bots.add(new Bot(userId, botCode, input));
            condition.signalAll();          //唤醒线程
        } finally {
            lock.unlock();
        }
    }

    //消费者(调用Consumer)
    public void consume(Bot bot) {
        Consumer consumer = new Consumer();
        consumer.startTimeOut(2000, bot);
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (bots.isEmpty())           //为空则暂定线程(多用户)
            {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();      //不写finally的原因是await()如果被唤醒自动解锁
                    break;
                }
            } else {
                // 消费对列头部
                Bot bot = bots.remove();
                lock.unlock();
                // 耗时操作，因此要在释放锁之后执行
                consume(bot);
            }
        }
    }
}
